package api

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"blockchain-api/internal/models"
	"blockchain-api/pkg/logger"
)

// createWallet 创建钱包
// @Summary 创建新钱包
// @Description 创建一个新的区块链钱包
// @Tags wallets
// @Accept json
// @Produce json
// @Param request body models.CreateWalletRequest true "创建钱包请求"
// @Success 201 {object} models.WalletResponse
// @Failure 400 {object} map[string]string
// @Failure 409 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /wallets [post]
func (s *Server) createWallet(c *gin.Context) {
	var req models.CreateWalletRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("Invalid request body:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
		return
	}

	// 创建钱包
	wallet, err := s.services.Wallet.CreateWallet(req.Name)
	if err != nil {
		logger.Error("Failed to create wallet:", err)
		c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
		return
	}

	// 获取余额（初始为0）
	balance := "0"

	response := models.WalletResponse{
		ID:        wallet.ID,
		Name:      wallet.Name,
		Address:   wallet.Address,
		Balance:   balance,
		CreatedAt: wallet.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	logger.Info("Wallet created successfully:", wallet.Name)
	c.JSON(http.StatusCreated, gin.H{
		"success": true,
		"message": "Wallet created successfully",
		"data":    response,
	})
}

// listWallets 列出所有钱包
// @Summary 列出所有钱包
// @Description 获取所有钱包的列表
// @Tags wallets
// @Produce json
// @Param limit query int false "限制返回数量"
// @Param offset query int false "偏移量"
// @Success 200 {object} map[string]interface{}
// @Failure 500 {object} map[string]string
// @Router /wallets [get]
func (s *Server) listWallets(c *gin.Context) {
	// 解析查询参数
	limitStr := c.DefaultQuery("limit", "10")
	offsetStr := c.DefaultQuery("offset", "0")

	limit, err := strconv.Atoi(limitStr)
	if err != nil || limit < 0 {
		limit = 10
	}

	offset, err := strconv.Atoi(offsetStr)
	if err != nil || offset < 0 {
		offset = 0
	}

	// 获取钱包列表
	wallets, err := s.services.Wallet.ListWallets(limit, offset)
	if err != nil {
		logger.Error("Failed to list wallets:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list wallets"})
		return
	}

	// 获取总数
	total, err := s.services.Wallet.GetWalletCount()
	if err != nil {
		logger.Error("Failed to get wallet count:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get wallet count"})
		return
	}

	// 构建响应
	var response []models.WalletResponse
	for _, wallet := range wallets {
		response = append(response, models.WalletResponse{
			ID:        wallet.ID,
			Name:      wallet.Name,
			Address:   wallet.Address,
			Balance:   "0", // 这里应该从区块链服务获取实际余额
			CreatedAt: wallet.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    response,
		"total":   total,
		"limit":   limit,
		"offset":  offset,
	})
}

// getWallet 获取钱包信息
// @Summary 获取钱包信息
// @Description 根据钱包名称获取钱包详细信息
// @Tags wallets
// @Produce json
// @Param name path string true "钱包名称"
// @Success 200 {object} models.WalletResponse
// @Failure 404 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /wallets/{name} [get]
func (s *Server) getWallet(c *gin.Context) {
	name := c.Param("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Wallet name is required"})
		return
	}

	// 获取钱包
	wallet, err := s.services.Wallet.GetWallet(name)
	if err != nil {
		logger.Error("Failed to get wallet:", err)
		c.JSON(http.StatusNotFound, gin.H{"error": "Wallet not found"})
		return
	}

	// 获取余额
	balance := "0" // 这里应该从区块链服务获取实际余额

	response := models.WalletResponse{
		ID:        wallet.ID,
		Name:      wallet.Name,
		Address:   wallet.Address,
		Balance:   balance,
		CreatedAt: wallet.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    response,
	})
}

// deleteWallet 删除钱包
// @Summary 删除钱包
// @Description 根据钱包名称删除钱包
// @Tags wallets
// @Produce json
// @Param name path string true "钱包名称"
// @Success 200 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /wallets/{name} [delete]
func (s *Server) deleteWallet(c *gin.Context) {
	name := c.Param("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Wallet name is required"})
		return
	}

	// 删除钱包
	if err := s.services.Wallet.DeleteWallet(name); err != nil {
		logger.Error("Failed to delete wallet:", err)
		c.JSON(http.StatusNotFound, gin.H{"error": "Wallet not found"})
		return
	}

	logger.Info("Wallet deleted successfully:", name)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Wallet deleted successfully",
	})
}

// getWalletBalance 获取钱包余额
// @Summary 获取钱包余额
// @Description 根据钱包名称获取钱包余额
// @Tags wallets
// @Produce json
// @Param name path string true "钱包名称"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /wallets/{name}/balance [get]
func (s *Server) getWalletBalance(c *gin.Context) {
	name := c.Param("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Wallet name is required"})
		return
	}

	// 获取钱包
	wallet, err := s.services.Wallet.GetWallet(name)
	if err != nil {
		logger.Error("Failed to get wallet:", err)
		c.JSON(http.StatusNotFound, gin.H{"error": "Wallet not found"})
		return
	}

	// 获取余额
	balance := "0" // 这里应该从区块链服务获取实际余额

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data": gin.H{
			"name":    wallet.Name,
			"address": wallet.Address,
			"balance": balance,
		},
	})
}